<template>
  <div class="login-container">
    <van-nav-bar
      class="app-nav-bar"
      title="登录"
      left-arrow
      @click-left="onClickLeft"
    />
    <van-form
      @submit="onSubmit"
      @failed="onFailed"
      validate-first
      :show-error="false"
      :show-error-message="false"
      ref="loginForm"
    >
      <van-cell-group>
        <van-field
          icon-prefix="iconfont"
          v-model="loginData.mobile"
          name="mobile"
          left-icon="shouji"
          placeholder="请输入手机号"
          type="tel"
          center
          clearable
          :rules="rules.mobilerule"
        />
        <van-field
          icon-prefix="iconfont"
          v-model="loginData.code"
          name="code"
          type="number"
          center
          clearable
          left-icon="yanzhengma"
          placeholder="请输入验证码"
          :rules="rules.coderule"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              native-type="button"
              @click="getCode"
              v-if="!showTime"
              :disabled="btnactive"
            >
              {{btnactive ? '请求中...' : '获取验证码'}}
            </van-button>
            <van-count-down
            :time="time"
            format=" ss 秒"
            @finish="showTime = !showTime"
            v-else
            />
          </template>
        </van-field>
      </van-cell-group>
      <div class="login-btn-wrap">
        <van-button type="info" block native-type="submit">登录</van-button>
      </div>
    </van-form>
    <p class="login-privacy">隐私条款</p>
  </div>
</template>

<script>
import { requestLogin, requestCode } from '@/api/user.js'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      rules: {
        mobilerule: [{ pattern: /^1[3-9]\d{9}/, message: '请填写正确的手机号' }],
        coderule: [{ pattern: /^\d{6}$/, message: '请填写正确的验证码' }]
      },
      loginData: {
        mobile: '17090086870',
        code: '246810'
      },
      showTime: false,
      time: 60 * 1000,
      // 获取验证码的按钮禁止的状态
      btnactive: false,
      // 显示当前登录页面前的页面路径，默认null
      beforeLogin: null
    }
  },
  mounted () {
    // this.test()
  },
  computed: {},
  methods: {
    ...mapMutations([
      'STORAGE_TOKEN'
    ]),
    // 登录
    onSubmit (formData) {
      requestLogin(formData).then(res => {
        this.$toast.success({
          message: '登陆成功',
          position: 'top'
        })
        // 登陆成功，存储toaken数据
        this.STORAGE_TOKEN(res.data.data)
        // 跳转到来到登录页的页面,如果没有前一页，则跳转到主页
        if (this.beforeLogin !== null) {
          this.$router.push(this.beforeLogin)
        } else {
          this.$router.push('/')
        }
      }).catch(err => {
        console.log(err, '失败')
        this.$toast.fail({
          message: '登陆失败',
          position: 'top'
        })
      })
    },
    onClickLeft () {
      // 头部返回按钮
      this.$router.go(-1)
    },
    onFailed (errorInfo) {
      if (errorInfo.errors && errorInfo.errors.length > 0) {
        this.$toast({
          message: errorInfo.errors[0].message,
          position: 'top'
        })
      }
    },

    /* 获取二维码 */
    async getCode () {
      // 防止请求数据时多次点击
      this.btnactive = true
      try {
        // 发送验证码前进行手机号验证
        // 如果校验成功，继续执行下一步请求获取验证码，否则被catch捕获校验失败
        await this.$refs.loginForm.validate('mobile')
        // 请求获取验证码
        // 获取成功后开始倒计时，否则catch捕获错误
        const response = await requestCode(this.loginData.mobile)
        this.showTime = true
        console.dir(response)
      } catch (err) {
        console.dir(err, 'hah')
        if (err && err.name === 'mobile') {
          this.$toast({
            message: err.message,
            position: 'top'
          })
        } else if (err && err.response && err.response.status === 429) {
          this.$toast({
            message: '发送太频繁了！',
            position: 'top'
          })
        } else {
          this.$toast({
            message: '发送失败！',
            position: 'top'
          })
        }
      }
      this.btnactive = false
    }
  },
  beforeRouteEnter (to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不！能！获取组件实例 `this`
    // 因为当守卫执行前，组件实例还没被创建
    next(vm => {
      // 通过 `vm` 访问组件实例
      // console.log(vm)
      // 将登录页面的前一个页面路径保存
      vm.beforeLogin = from.path
      console.log(vm.beforeLogin)
    })
  }
}

</script>

<style lang="less" scoped>
.login-container {
  position: relative;
  height: 100%;
  .van-cell {
    padding: 15px 20px;
    .van-field__left-icon {
      margin-right: 19px;
      .iconfont {
        font-size: 18.5px;
      }
    }
    /deep/ .van-field__body {
      font-size: 13px;
      .van-field__button {
        padding-left: 10px;
        border-left: 1px solid #eeeeee;
        .van-button,
        .van-count-down {
          width: 79px;
          height: 23px;
          font-size: 11px;
          line-height: 23px;
          background-color: #ededed;
          color: #666666;
          border-radius: 23px;
          border: none;
          padding: 0;
          text-align: center;
        }
      }
    }
  }
  .login-btn-wrap {
    padding: 26.5px 14px;
    .van-button {
      background-color: #6db4fb;
      border: none;
      font-size: 15px;
    }
  }
  .login-privacy {
    position: absolute;
    bottom: 27px;
    left: 0;
    width: 100%;
    margin: 0;
    font-size: 12.5px;
    color: #666666;
    text-align: center;
  }
}
</style>
